package thomas.javase.file;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.function.Predicate;
import java.util.stream.Stream;

//@Slf4j
public class FileUtil {

    /**
     * copy files from one folder to another
     * @param sourceFolder
     * @param destinationFolder
     * Note: if the file is not ready in the source folder, then it may throws this exception
     * java.nio.file.FileSystemException: F:\temp\test\file\source\CentOS-7-x86_64-DVD-1810.iso -> F:\temp\test\file\destination\CentOS-7-x86_64-DVD-1810.iso:
     * The process cannot access the file because it is being used by another process.
     */
    public static void fileMove(String sourceFolder, String destinationFolder){
        try(Stream<Path> stream = Files.list(Paths.get(sourceFolder))){
            stream.map(Path::toAbsolutePath).filter(isRegularFile()).forEach(
                    path -> {
                        try {
                            Files.move(path, Paths.get(destinationFolder, path.getFileName().toString()), StandardCopyOption.REPLACE_EXISTING);
                            System.out.println(String.format("Moved file %s from %s to %s", path.getFileName().toString(), sourceFolder, destinationFolder));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @return
     */
    private static Predicate<Path> isRegularFile(){
        return path -> {
            try {
                BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
                return fileAttributes.isRegularFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        };
    }
}
